package com.gitee.qdbp.jdbc.result;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import com.gitee.qdbp.able.convert.ObjectTypeConverter;
import com.gitee.qdbp.jdbc.plugins.DbPluginHelper;

/**
 * 获取单列数据
 *
 * @author zhaohuihua
 * @version 20200722
 */
public class SingleColumnMapper<T> implements RowMapper<T>, DbPluginHelper.Aware {

    /** 插件容器 **/
    protected DbPluginHelper plugins;

    private final String columnName;
    private final Class<T> valueClazz;

    public SingleColumnMapper(String columnName, Class<T> valueClazz) {
        this.columnName = columnName;
        this.valueClazz = valueClazz;
    }

    @Override
    public void setPlugins(DbPluginHelper plugins) {
        this.plugins = plugins;
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Object value = null;
        for (int i = 1; i <= columnCount; i++) {
            String columnName = JdbcUtils.lookupColumnName(rsmd, i);
            if (columnName.equals(this.columnName)) {
                value = JdbcUtils.getResultSetValue(rs, i, valueClazz);
                break;
            }
        }
        ObjectTypeConverter converter = plugins.getObjectTypeConverter();
        return converter.convert(value, valueClazz);
    }
}
